using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/**
游戏主逻辑 游戏场景 碰撞检测等
**/
public class Game : MonoBehaviour
{
    // 当前激活的球
    public Ball activeBall { get; private set; }

    //篮筐
    public Basket basket { get; private set; }

    private float forceMagnitude = 0;
    private Vector2 forceDirection;

    public void Awake()
    {
        activeBall = GetComponent<Ball>();
        basket = GetComponent<Basket>();
    }
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                // 获取触摸位置
                Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane + 5));
                activeBall.GenerateBall(touchPosition);
                activeBall.BallInstance.GetComponent<Rigidbody>().useGravity = false;
                activeBall.BallInstance.GetComponent<Rigidbody>().velocity = Vector3.zero;
            }
            // 触摸移动
            if (touch.phase == TouchPhase.Moved)
            {
                // 获取触摸位置
                Vector3 touchPosition = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, Camera.main.nearClipPlane + 5));
                activeBall.BallInstance.transform.position = touchPosition;
                // 计算 方向 和 力量
                // 滑动距离
                Vector2 delta = touch.deltaPosition;
                // 力量大小    
                forceMagnitude = delta.magnitude;
                // 力量方向 单位向量
                forceDirection = delta.normalized;
                // Debug.Log($"滑动距离 {delta}");
            }
            if (touch.phase == TouchPhase.Ended)
            {
                if (forceMagnitude != 0)
                {
                    if (forceMagnitude > 40)
                    {
                        forceMagnitude = 40;
                    }
                    // Debug.Log($"力量大小 {forceMagnitude}");
                    // Debug.Log($"单位向量 {forceDirection}");
                    Vector3 worldForceDirection = new Vector3(forceDirection.x, forceDirection.y / 2, forceDirection.y);
                    activeBall.BallInstance.GetComponent<Rigidbody>().useGravity = true;
                    activeBall.BallInstance.GetComponent<Rigidbody>().AddForce(worldForceDirection * forceMagnitude * 10, ForceMode.Force);
                }
            }
        }

    }
}
